/**
 * @author ydiego
 * @date on 2020/08/22
 * @email yudeguo@hzxituan.com
 */
const dayjs = require('dayjs')

function initIntervalSql({type = 'day', filter = ''}) {
  let sql = "";
  const distinct = filter === 'uv' ? 'distinct member_id,' : ''
  if (type === 'day') {
    sql = `select ${distinct} concat(date(action_time), ' ', HOUR(action_time), ':', IF(floor( MINUTE ( action_time ) / 30 ) * 30 > 0, '00', '30')) AS date from xt_buried_point_process`
  } else if (type === 'week'){
    sql = `select ${distinct} concat(date(action_time), ' ', CONVERT(FLOOR(HOUR(action_time) / 6) * 6, SIGNED) , ':', '00') AS date from xt_buried_point_process`
  } else if (type === 'month') {
    sql = `select ${distinct} date(action_time) AS date from xt_buried_point_process`
  } else if (type === 'page') {
    sql = `select LEFT(page_url, INSTR(page_url, '?') - 1) as page_url from xt_buried_point_process`
  } else {
    sql = 'select count(1) from xt_buried_point_process'
  }
  return sql
}

function initWhere(conditions = []) {
  if (!conditions.length) return ''
  let where = 'where'
  conditions.forEach((condition, index) => {
    where += ` ${condition.key} ${condition.symbol || '='} ${condition.valueType ? condition.value :`'${condition.value}'`}`
    if (index + 1 !== conditions.length) {
      where += ' and'
    }
  })
  return where === 'where' ? '' : where
}

function initSearchSql(option) {
  const {
    date_type = 'day', // 时间轴 日day 周week 月month
    filter = 'pv', // pv or uv
    env = 'prod',  // prod pre dev test
    type = '',     // 页面
    platform = '', // h5 wx-mini ios android wx-h5
    action_id = '' // 埋点标识
  } = option

  const initIntervalOption = {
    type: date_type,
    filter
  }

  const conditions = []

  if (env) {
    conditions.push({
      key: 'env',
      value: env
    })
  }

  if (['pv', 'uv'].includes(filter)) {
    conditions.push({
      key: 'moon_type',
      value: 'pu'
    })
  }
  if (platform) {
    conditions.push({
      key: 'platform',
      value: platform
    })
  }

  if (action_id) {
    conditions.push({
      key: 'action_id',
      value: action_id
    })
  }

  let aliasRes = ''

  if (date_type === 'day') {
    const todayOfStart = dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss')
    const yesterdayOfStart = dayjs().subtract(1, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss')
    conditions.push({
      key: 'action_time',
      symbol: '>',
      valueType: 'origin',
      value: `'${yesterdayOfStart}'`
    })
    aliasRes = `,if(date > '${todayOfStart}' , '今日', '昨日') as type`
  } else if (date_type === 'week') {
    // 默认一周开始为星期天  如果要配置周一开始需要添加插件 https://day.js.org/docs/zh-CN/plugin/week-day
    const lastWeekStart = dayjs().subtract(1, 'week').startOf('week').add(1, 'day').format('YYYY-MM-DD HH:mm:ss')

    conditions.push({
      key: 'action_time',
      symbol: '>=',
      valueType: 'origin',
      value: `'${lastWeekStart}'`
    })
    aliasRes = `, if(WEEK(date, 1) < WEEK(NOW(), 1) , '上周', '本周') as type`
  } else if (date_type === 'month') {
    const lastMonthStart = dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD HH:mm:ss')
    conditions.push({
      key: 'action_time',
      symbol: '>=',
      valueType: 'origin',
      value: `'${lastMonthStart}'`
    })

    aliasRes = `, if(month(date) < month(NOW()) , '上月', '本月') as type`
  }

  let sql = `select DATE_FORMAT(date, '%Y-%m-%d %H:%i') AS date, count(1) as value ${aliasRes} from (${initIntervalSql(initIntervalOption)} ${initWhere(conditions)}) AS a group by a.date order by UNIX_TIMESTAMP(a.date) asc`
  if (type === 'page') {
    initIntervalOption.type = type
    aliasRes = ''
    sql = `select page_url, count(1) as value ${aliasRes} from (${initIntervalSql(initIntervalOption)} ${initWhere(conditions)}) AS a group by a.page_url`
  }
  return sql
}

module.exports = initSearchSql